package com.bangdream.michelia.view.fragment.exam;

import android.content.Intent;
import android.graphics.RectF;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.ExamContract;
import com.bangdream.michelia.entity.exam.AnswerBean;
import com.bangdream.michelia.entity.exam.ExamBean;
import com.bangdream.michelia.entity.exam.ExamQuestBean;
import com.bangdream.michelia.entity.exam.ExamResultDetailsBean;
import com.bangdream.michelia.entity.exam.ExamResultItemBean;
import com.bangdream.michelia.entity.exam.SubjectBean;
import com.bangdream.michelia.entity.exam.SubjectInfoBean;
import com.bangdream.michelia.presenter.ExamPresenter;
import com.bangdream.michelia.utils.ExtractMessageUtils;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.view.activity.exam.ExamHelper;
import com.bangdream.michelia.view.activity.exam.ExamResultActivity;
import com.bangdream.michelia.view.activity.exam.OnMainActivityListener;
import com.bangdream.michelia.view.custom.fillblanks.ReplaceSpan;
import com.bangdream.michelia.view.custom.fillblanks.SpansManager;

import java.util.List;

/**
 * @date on 2018/8/18 17:25
 * @email 909732184@qq.com
 * 考试-填空题
 */
public class FillBlankFragment extends BaseAnswerFragment<ExamContract.IExamView,ExamPresenter<ExamContract.IExamView>>
        implements ReplaceSpan.OnClickListener ,View.OnClickListener,ExamContract.IExamView{
    private View view;
    private String mTestStr = "";
    private TextView mTvContent;
    private EditText mEtInput;
    private SpansManager mSpansManager;
    private LinearLayout btnRemember;
    private ImageView ivRemember;
    //默认不标记
    private boolean isRemember = false;
    private TextView tvDescribe,tvIndex,tvTotalIndex,tvTime;
    private int nmIndex,nmTotalIndex;
    private SubjectBean subjectBean;
    private SubjectInfoBean data;
    //本次考试的考试id
    private String examId;
    private OnMainActivityListener onMainActivityListener;
    private boolean isNext;
    //试卷id
    private String paperId;
    //需要提交的答案
    private String stAnswer = "";
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fill_blank_fragment,container,false);
        return view;
    }

    @Override
    public ExamPresenter createPresenter() {
        return new ExamPresenter();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView();
        setListener();
    }

    private void initView(){
        if(getArguments()!=null){
            examId = getArguments().getString("examId");
            paperId = getArguments().getString("paperId");
            nmIndex = getArguments().getInt("index");
            nmTotalIndex = getArguments().getInt("totalIndex");
            subjectBean = getArguments().getParcelable("data");
        }
        tvTime = view.findViewById(R.id.tvTime);
        tvIndex = view.findViewById(R.id.tvIndex);
        tvTotalIndex = view.findViewById(R.id.tvTotalIndex);
        mTvContent = view.findViewById(R.id.tv_content);
        mEtInput = view.findViewById(R.id.et_input);
        mSpansManager = new SpansManager(this,mTvContent,mEtInput);
        btnRemember = view.findViewById(R.id.btnRemember);
        ivRemember = view.findViewById(R.id.ivRemember);
        tvDescribe = view.findViewById(R.id.tvDescribe);
        pd.setCanceledOnTouchOutside(false);
    }

    @Override
    public void loadData() {
        if(subjectBean!=null) {
            mPresenter.getSubjectDetails(subjectBean.getId(),"0",pd);
        }
    }

    private void setViewData(){
        if(data==null)
            return;
        SubjectInfoBean.QuestionInfoListBean question = data.getQuestionInfoList();
        if(question==null)
            return;
        //mTestStr = "1.注塑磨具可以分为"+SpansManager.SPILT_TAG+"和"+SpansManager.SPILT_TAG+"零件？";
        mTestStr = question.getDescription()+"";
        //提取出括号内的内容设置为填空题的空位
        List<String> stringList = ExtractMessageUtils.extractMessageByRegular(mTestStr);
        L.d(JSON.toJSONString(stringList));
        if(stringList!=null){
            for(int i = 0;i<stringList.size();i++){
                String str = "("+stringList.get(i)+")";
                if(mTestStr.contains(str)){
                    mTestStr = mTestStr.replace(str,SpansManager.SPILT_TAG);
                    //这个替换会留下括号
                    //mTestStr = mTestStr.replaceFirst(str,SpansManager.SPILT_TAG);
                }
            }
        }
        mSpansManager.doFillBlank(mTestStr);
        tvDescribe.setText("(填空题2分)");
        tvIndex.setText((nmIndex+1)+"");
        tvTotalIndex.setText("/"+nmTotalIndex+"");
    }

    private void setListener() {
        btnRemember.setOnClickListener(this);
    }

    @Override
    public void OnClick(TextView v, int id, ReplaceSpan span) {
        mSpansManager.setData(mEtInput.getText().toString(),null, mSpansManager.mOldSpan);
        mSpansManager.mOldSpan = id;
        //如果当前span身上有值，先赋值给et身上
        mEtInput.setText(TextUtils.isEmpty(span.mText)?"":span.mText);
        mEtInput.setSelection(span.mText.length());
        span.mText = "";
        //通过rf计算出et当前应该显示的位置
        RectF rf = mSpansManager.drawSpanRect(span);
        //设置EditText填空题中的相对位置
        mSpansManager.setEtXY(rf);
        mSpansManager.setSpanChecked(id);
    }

    public List<String> getMyAnswerStr(){
        mSpansManager.setLastCheckedSpanText(mEtInput.getText().toString());
        return mSpansManager.getMyAnswer();
    }

    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.btnRemember:
                setRemember();
                break;
                default:break;
        }
    }

    private void setRemember() {
        isRemember = !isRemember;
        if(isRemember){
            ivRemember.setImageResource(R.mipmap.kaoshi_bj_answer_b);
        }else {
            ivRemember.setImageResource(R.mipmap.kaoshi_bj_answer_a);
        }
        ExamHelper.getInstance().SignSetSelect(nmIndex);
    }

    @Override
    public void setTime(String stTime) {
        tvTime.setText("剩余时间 "+stTime);
    }

    @Override
    public void saveAnswer(boolean isFinish,boolean isNext) {
        this.isNext = isNext;
        if(data==null||paperId==null||examId==null){
            if(isFinish){
                if(ExamHelper.getInstance().getAnswerBeans()!=null){
                    AnswerBean answerBean = new AnswerBean();
                    for (AnswerBean bean:ExamHelper.getInstance().getAnswerBeans()){
                        answerBean = bean;
                    }
                    answerBean.setIsFinish("1");
                    mPresenter.actionSubmitExam(answerBean,isFinish,pd);
                    return;
                }
            }
            showText("数据错误");
            getActivity().finish();
            return;
        }
        SubjectInfoBean.QuestionInfoListBean question = data.getQuestionInfoList();
        if(question==null)
            return;
        //提取出括号内的内容设置为填空题的空位 最终提交的答案
        stAnswer = question.getDescription()+"";
        List<String> AnswerStr = getMyAnswerStr();
        //将题目中需要填写答案的地方截取成list
        List<String> stringList = ExtractMessageUtils.extractMessageByRegular(stAnswer);
        if(stringList!=null){
            for(int i = 0;i<stringList.size();i++){
                //String str = "("+stringList.get(i)+")";
                //只替换括号内的内容
                String str = stringList.get(i);
                if(stAnswer.contains(str)){
                    L.d(str+"替换为"+(AnswerStr.size()>i?AnswerStr.get(i):AnswerStr.get(AnswerStr.size()-1)));
                    stAnswer = stAnswer.replace(str,AnswerStr.size()>i?AnswerStr.get(i):AnswerStr.get(AnswerStr.size()-1));
                    //这个替换会留下括号
                    //mTestStr = mTestStr.replaceFirst(str,SpansManager.SPILT_TAG);
                }
            }
        }
        L.d(stAnswer);
        //是否已答
        boolean isAnswer = false;
        if(AnswerStr!=null&&AnswerStr.size()>0) {
            for(String string :AnswerStr){
                if(string!=null&&string.length()>0){
                    isAnswer = true;
                    break;
                }
            }
        }
        ExamHelper.getInstance().getIsAnswerBegin().set(nmIndex,isAnswer);
        //提交
       submit(isFinish);
    }

    private void submit(boolean isFinish) {
        AnswerBean answerBean = new AnswerBean();
        answerBean.setAnswer(stAnswer);
        answerBean.setExamId(examId);
        //answerBean.setExamStart(stAnswerNos);
//        answerBean.setId(data.getId());
        answerBean.setId(subjectBean.getId());
        answerBean.setPaperId(paperId);
        SubjectInfoBean.QuestionInfoListBean question = data.getQuestionInfoList();
        if(question!=null)
            answerBean.setQuestionId(question.getId());
        answerBean.setUserId(AppCurrentUser.getInstance().getUserInfo().getId());
        //1：交卷 0：不交卷
        if(isFinish) {
            answerBean.setIsFinish("1");
        }else {
            answerBean.setIsFinish("0");
        }
        mPresenter.actionSubmitExam(answerBean,isFinish,pd);
        ExamHelper.getInstance().putAnswer(answerBean);
    }

    @Override
    public void setExamList(boolean isSuccess, int page, List<ExamBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectList(boolean isSuccess, List<SubjectBean> data, String stDescribe) {

    }

    @Override
    public void setSubjectDetails(boolean isSuccess, SubjectInfoBean data, String stDescribe) {
        if(isSuccess){
            this.data = data;
            setViewData();
        }else {

        }
    }

    @Override
    public void initExamId(boolean isSuccess, String examId, String stDescribe) {

    }

    @Override
    public void actionSubmitExam(boolean isSuccess,boolean isFinish, String stDescribe) {
        if(isSuccess){
            if(isFinish){
                showText("提交成功");
                //TODO
                Intent intent = new Intent(getActivity(),ExamResultActivity.class);
                intent.putExtra("examId", examId);
                startActivity(intent);
                getActivity().finish();
            }else {
                if(onMainActivityListener!=null){
                    if(isNext){
                        onMainActivityListener.onPageToNext();
                    }else {
                        onMainActivityListener.onPageToLast();
                    }
                }
            }
        }
    }

    @Override
    public void actionSubmitQuest(boolean isSuccess, boolean isFinish, String stDescribe) {

    }

    @Override
    public void setExamResultList(boolean isSuccess, List<ExamResultItemBean> data, String stDescribe) {

    }

    @Override
    public void setExamResultDetails(boolean isSuccess, ExamResultDetailsBean data, String stDescribe) {

    }

    @Override
    public void setExamQuestList(boolean isSuccess, List<ExamQuestBean> data, String stDescribe) {

    }

    @Override
    public void setExamQuList(boolean isSuccess, List<ExamBean> data, String stDescribe) {


    }

    @Override
    public void setOnMainActivityListener(OnMainActivityListener onMainActivityListener) {
        this.onMainActivityListener = onMainActivityListener;
    }
}
